<!DOCTYPE html>
<html>
<!--
Copyright 2013 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<head>
<title>Model Tests</title>
<script src="third_party/closure/closure/goog/base.js"></script>
<script src="platform/compat.js"></script>
<script src="side_table.js"></script>
<script src="path.js"></script>
<script src="model.js"></script>
<script src="script_value_binding.js"></script>
<script src="text_replacements_binding.js"></script>
<script src="test_common.js"></script>

<script>
goog.require('goog.testing.jsunit');
</script>
</head>
<body>
<script>

function testTextReplacementsBinding() {
  var lastSeenValue;
  var changeCount = 0;
  var observer = {
    valueChanged: function(b) {
      assertEquals(binding, b);
      changeCount++;
      lastSeenValue = b.value;
    }
  };

  var model = {first: 'First', last: 'Last'};
  var binding = new TextReplacementsBinding(model, null,
                                            'Hello {{first}} {{last}}!',
                                            observer);

  assertEquals('Hello First Last!', binding.value);

  model.last = 'Fry';
  Model.dirtyCheck();
  assertEquals('Hello First Fry!', binding.value);
  assertEquals(1, changeCount);
  assertEquals('Hello First Fry!', lastSeenValue);

  model.first = 'Philip';
  Model.dirtyCheck();
  assertEquals('Hello Philip Fry!', binding.value);
  assertEquals(2, changeCount);
  assertEquals('Hello Philip Fry!', lastSeenValue);
}

function testTextReplacementsBindingWithDelegate() {
  var observer = {
    valueChanged: function(binding) {

    }
  };

  function delegate(text) {
    var re = /\w+(\.\w+)*/g;

    function replacePathWithIdent(path) {
      return path.replace(/\W/g, '_');
    }

    var paths = text.match(re);
    var args = paths.map(replacePathWithIdent);
    var expr = text.replace(re, replacePathWithIdent);
    var toTarget = new Function(args.join(','), 'return (' + expr + ')');
    return [paths, toTarget];
  }

  var model = {v: {x: 1, y: 2}};
  var binding = new TextReplacementsBinding(model, delegate,
                                            '{{v.x}} + {{v.y}} = {{v.x + v.y}}',
                                            observer);

  assertEquals('1 + 2 = 3', binding.value);

  model.v.x = 4;
  Model.dirtyCheck();
  assertEquals('4 + 2 = 6', binding.value);

  model.v = {x: 5, y: 6};
  Model.dirtyCheck();
  assertEquals('5 + 6 = 11', binding.value);
}

</script>
</body>
</html>
